package com.yh.csx.crm.service;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yh.csx.crm.core.enums.CooperationModeEnum;
import com.yh.csx.crm.core.enums.CustomerStatusEnum;
import com.yh.csx.crm.core.exception.BusinessException;
import com.yh.csx.crm.service.request.DevCustomerAddReq;
import com.yh.csx.crm.service.request.DevCustomerListReq;
import com.yh.csx.crm.core.util.BeanUtils;
import com.yh.csx.crm.core.util.DateUtils;
import com.yh.csx.crm.core.util.LevenshteinUtils;
import com.yh.csx.crm.dao.CustomerMapper;
import com.yh.csx.crm.dao.CustomerVisitRecordMapper;
import com.yh.csx.crm.dao.SysCustomerCategoryMapper;
import com.yh.csx.crm.dao.SysSalesPermissionMapper;
import com.yh.csx.crm.po.Customer;
import com.yh.csx.crm.po.CustomerVisitRecord;
import com.yh.csx.crm.po.SysCustomerCategory;
import com.yh.csx.crm.qo.CustomerListQo;
import com.yh.csx.crm.service.response.AppCustomerVisitResp;
import com.yh.csx.crm.service.response.DevCustomerCheckResp;
import com.yh.csx.crm.service.response.DevCustomerListResp;
import com.yh.csx.crm.service.response.DevCustomerResp;
import com.yh.csx.crm.service.vo.PageWrap;
import com.yh.csx.crm.service.vo.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * DevCustomerService class
 *
 * @author huyalin
 * @date 2019/4/15
 */
@Service
@Slf4j
public class DevCustomerService {

    @Value("${dev.customer.limit}")
    private int devCustomerLimit;

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private SysSalesPermissionMapper sysSalesPermissionMapper;

    @Autowired
    private GeoService geoService;

    @Autowired
    private SysCustomerCategoryMapper sysCustomerCategoryMapper;

    @Autowired
    private CustomerVisitRecordMapper customerVisitRecordMapper;

    @Autowired
    private CustomerVisitService customerVisitService;

    /**
     * 获取客户详情
     * @param id
     * @return
     */
    public DevCustomerResp getCustomer(Long id) {
        Customer customer = customerMapper.selectByPrimaryKey(id);
        DevCustomerResp devCustomerResp = BeanUtils.convert(DevCustomerResp.class, customer);
        SysCustomerCategory sysCustomerCategory = sysCustomerCategoryMapper.selectByPrimaryKey(devCustomerResp.getCustomerCategoryId());
        if (sysCustomerCategory != null) {
            devCustomerResp.setCustomerCategory(sysCustomerCategory.getFullName());
        }
        // 拜访记录
        devCustomerResp.setVisitList(BeanUtils.convertList(AppCustomerVisitResp.class, customerVisitService.findCustomerLastOneForEachType(id), (t, r) -> {
            if (t.getVisitImgsUrl() != null) r.setVisitImgs(t.getVisitImgsUrl().split(","));
        }));
        return devCustomerResp;
    }


    /**
     * 获取我的客户列表
     * @param req
     * @return
     */
    public PageWrap<List<DevCustomerListResp>> getDevCustomerList(User user, DevCustomerListReq req) {
        CustomerListQo qo = BeanUtils.convert(CustomerListQo.class, req);
        qo.setType("dev");
        if (Objects.nonNull(req.getBeginDate()) && Objects.nonNull(req.getEndDate())) {
            qo.setBeginDateStr(DateUtils.formatDate(qo.getBeginDate()));
            qo.setEndDateStr(DateUtils.formatDate(qo.getEndDate()));
        }
        qo.setStatus(CustomerStatusEnum.DEV.getCode());
        if (StringUtils.isNotBlank(req.getLocation())) {
            String[] values = req.getLocation().split(",");
            qo.setLatitude(Double.valueOf(values[0]));
            qo.setLongitude(Double.valueOf(values[1]));
            qo.setOrderField(2);
        }
        //公海
        if (req.getListType() != null && req.getListType().equals("01")) {
            qo.setSubordinateUserIdList(Arrays.asList(0L));
        }
        //私海
        else if (req.getListType() != null && req.getListType().equals("02")) {
            qo.setSalesUserId(user.getUserId());
//            List<Long> subordinateUserIdList = sysSalesPermissionMapper.selectSubordinateByUserId(user.getUserId());
//            if (CollectionUtils.isEmpty(subordinateUserIdList)) {
//                subordinateUserIdList = Arrays.asList(user.getUserId());
//            }
//            qo.setSubordinateUserIdList(Arrays.asList(user.getUserId()));
//            qo.setSubordinateUserIdList(subordinateUserIdList);
        }
        //全部
        else {
//            List<Long> subordinateUserIdList = sysSalesPermissionMapper.selectSubordinateByUserId(user.getUserId());
//            if (CollectionUtils.isEmpty(subordinateUserIdList)) {
//                subordinateUserIdList.add(user.getUserId());
//            }
//            subordinateUserIdList.add(0L);
//            qo.setSubordinateUserIdList(subordinateUserIdList);
        }
        Page<Object> page = PageHelper.startPage(req.getPageNum(), req.getPageSize());
        List<Customer> customerList = customerMapper.selectByExample(qo);
        List<DevCustomerListResp> devCustomerListResps = new ArrayList<>();
        customerList.forEach(customer -> {
            DevCustomerListResp devCustomerListResp = BeanUtils.convert(DevCustomerListResp.class, customer);
            devCustomerListResp.setListType(devCustomerListResp.getSalesUserId() != 0L ? "02" : "01");
            SysCustomerCategory sysCustomerCategory = sysCustomerCategoryMapper.selectByPrimaryKey(devCustomerListResp.getCustomerCategoryId());
            if (sysCustomerCategory != null) {
                devCustomerListResp.setCustomerCategory(sysCustomerCategory.getFullName());
            }
            if (devCustomerListResp.getSalesUserId().compareTo(user.getUserId()) != 0 && devCustomerListResp.getSalesUserId() != 0L) {
                devCustomerListResp.setDetailsFlag(false);
            }
            devCustomerListResp.setAddress(customer.getRegionProvinceName() + "/" + customer.getRegionCity() + "/" + customer.getRegionArea());

            List<CustomerVisitRecord> visitRecords = customerVisitRecordMapper.selectLastOneForEachType(customer.getId());
            if (!visitRecords.isEmpty()) {
                devCustomerListResp.setLastVisitTime(visitRecords.get(0).getVisitTime());
            }
            devCustomerListResps.add(devCustomerListResp);
        });
        PageWrap pageWrap = new PageWrap<>();
        pageWrap.setValue(page);
        pageWrap.setResult(devCustomerListResps);
        return pageWrap;
    }

    /**
     * 判断私海容量是否超限
     * @param user
     * @return
     */
    public boolean devCustomerLimit(User user) {
        DevCustomerListReq devCustomerListReq = new DevCustomerListReq();
        devCustomerListReq.setListType("02");
        int totalNum = this.getDevCustomerList(user, devCustomerListReq).getTotalNum();
        if (totalNum >= devCustomerLimit) {
            return true;
        }
        return false;
    }

    /**
     * 新增和编辑待开发客户
     * @param req
     */
    public void addDevCustomer(User user, DevCustomerAddReq req) {
        Customer customer = null;
        if (req.getId() != null) {
            customer = customerMapper.selectByPrimaryKey(req.getId());
            if (customer == null) {
                throw new BusinessException("客户不存在");
            }
            org.springframework.beans.BeanUtils.copyProperties(req, customer);
            customer.setUpdateTime(null);
            customer.setUpdateBy(user.getUserName());
            if (customerMapper.selectCountByCustomerName(req.getCustomerName(), req.getId()) > 0) {
                throw new BusinessException("客户名称已存在");
            }

            if (log.isDebugEnabled()) {
                log.debug("编辑客户信息" + customer.toString());
            }
        } else {
            if (this.devCustomerLimit(user)) {
                throw new BusinessException("新建失败，已超过私海容量限制");
            }
            customer = BeanUtils.convert(Customer.class, req);
            customer.setFilePath("[]");
            customer.setSalesUserId(user.getUserId());
            customer.setSalesUserName(user.getUserName());
            customer.setCustomerStatus(CustomerStatusEnum.DEV.getCode());
            customer.setCreateBy(user.getUserName());
            customer.setUpdateBy(user.getUserName());
            if (customerMapper.selectCountByCustomerName(req.getCustomerName(), null) > 0) {
                throw new BusinessException("客户名称已存在");
            }
            if (log.isDebugEnabled()) {
                log.debug("入库客户信息" + customer.toString());
            }
        }
        if (StringUtils.isNotBlank(req.getRegionProvinceName()) &&
                StringUtils.isNotBlank(req.getRegionCity()) &&
                StringUtils.isNotBlank(req.getRegionArea())) {
            double[] resolveAddress = null;
            try {
                resolveAddress = geoService.resolveAddress(req.getRegionProvinceName() +
                        req.getRegionCity() + req.getRegionArea() + req.getAddressDetails());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
            if (resolveAddress != null) {
                customer.setLongitude(BigDecimal.valueOf(resolveAddress[0]));
                customer.setLatitude(BigDecimal.valueOf(resolveAddress[1]));
            }
        }


        if (req.getId() != null) {
            customerMapper.updateByPrimaryKeySelective(customer);
        } else {
            customerMapper.insertSelective(customer);
        }

//        Customer beforCustomer = null;
//        if (Objects.nonNull(req.getId()) && Objects.nonNull(beforCustomer = customerMapper.selectByPrimaryKey(req.getId()))) {
//            if (customerMapper.selectCountByCustomerName(req.getCustomerName(), req.getId()) > 0) {
//                throw new BusinessException("客户名称已存在");
//            }
//
//            if (log.isDebugEnabled()) {
//                log.debug("编辑客户信息" + customer.toString());
//            }
//            customerMapper.updateByPrimaryKeySelective(beforCustomer);
//
//        } else {
//            if (customerMapper.selectCountByCustomerName(req.getCustomerName(), null) > 0) {
//                throw new BusinessException("客户名称已存在");
//            }
//            customerService.initCustomer(user, customer);
//            if (log.isDebugEnabled()) {
//                log.debug("入库客户信息" + customer.toString());
//            }
//            customerMapper.insertSelective(customer);
//        }
    }

    /**
     * 校验已存在的客户
     * @param customerName
     * @return
     */
    public List<DevCustomerCheckResp> checkDevCustomer(String customerName) {
        List<DevCustomerCheckResp> resultList = new ArrayList<>();
        if (StringUtils.isNotBlank(customerName)) {
            for (int i = 1; ; i++) {
                Page<Object> page = PageHelper.startPage(i, 100);
                List<Customer> customerList = customerMapper.selectAll();
                customerList.forEach(customer -> {
                    double ratio = LevenshteinUtils.getSimilarityRatio(customer.getCustomerName(), customerName);
                    if (ratio >= 0.8) {
                        resultList.add(new DevCustomerCheckResp(customer.getCustomerName(),
                                customer.getRegionProvinceName() + customer.getRegionCity() + customer.getRegionArea()));
                    }
                });
                if (i >= page.getPages()) {
                    break;
                }
            }
        }
        return resultList;
    }


    public void toCustomer(User user, Long customerId) {
        Customer customer = customerMapper.selectByPrimaryKey(customerId);
        if (customer == null) {
            throw new BusinessException("客户不存在");
        }
        customer.setCustomerStatus(CustomerStatusEnum.PENDING.getCode());
        customerMapper.updateByPrimaryKeySelective(customer);
    }
}
